#include <iostream>
#include <iomanip>

#include <fcntl.h>

#include "IOError.h"
#include "Counter_DL636G1.h"
#include "DigitalIO_DL636F.h"
#include "ADC_DL642A.h"

using namespace std;


int main(int argc, char *argv[])
{
  const char *device="/tmp/sis1100_00remote";
  int crate;

  cout << "dackel 0.0.0" << endl << endl;

  // open sis1100/3100 pci-to-vme link
  if( !(crate=open(device, O_RDWR, 0)) )
  {
    cout << "ERROR: could not open \"" << device << "\"" << endl;
    exit(1);
  }
  
  vmesysreset(crate);

  // instantiate counter object
  Counter_DL636G1 counter1(crate,0x4420);

  // instantiate io object
  DigitalIO_DL636F io1(crate,0x4400);

  // instantiate adc object
  ADC_DL642A adc1(crate,0xb200);

  try {
    counter1.reset();

    // output counter values
    cout << "counter1.a == " << counter1.getA() << endl;
    cout << "counter1.b == " << counter1.getB() << endl;
    cout << "counter1.c == " << counter1.getC() << endl << endl;

    // init adc1.
    cout << "adc1: init" << endl;
    adc1.reset();
    adc1.clearFIFO();
    adc1.setEnable(1);

    // display current state of adc1
    cout << "adc:"
	 << " hitcounter = " << adc1.getHitCounter()
	 << " enable = " << adc1.isEnabled() 
         << " status = " << setw(4) << setfill('0') << adc1.getStatus()
         << " busy = " << io1.getInput() << endl;

    
    // enable gate of adc1 via output 1 of io1
    cout << "enabling gate of adc1" << endl; io1.setO1(1);

#if 0
    // display current state of adc1
    cout << "adc:"
	 << " hitcounter = " << adc1.getHitCounter()
	 << " enable = " << adc1.isEnabled() 
         << " status = " << setw(4) << setfill('0') << adc1.getStatus()
         << " busy = " << io1.getInput() << endl;

    cout << "measuring..." << endl;
#endif

   usleep(5000);


    // disable gate of adc1 via output 1 of io1
    io1.setO1(0);
    cout << "gate of adc1 disabled" << endl; 

    // display current state of adc1
    cout << "adc:"
	 << " hitcounter = " << adc1.getHitCounter()
	 << " enable = " << adc1.isEnabled() 
         << " status = " << setw(4) << setfill('0') << adc1.getStatus()
         << " busy = " << io1.getInput() << endl;


    // read out channels of adc1
    for(int i=0; i<3; i++)
    {
      cout << "adc1, channel " << i << ": " << adc1.readFIFO(i) << endl;
    }

    usleep(100);
  }
  catch( IOError ioe ) {
    cout << "catched IOError expection: " << ioe.getMsg() << endl 
	 << "param=" << ioe.getParam() << endl;
  }
    

  close(crate);

  return 0;
}
